有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在SpringBootApplication类中使用服务的java抛出NullPointerException

我对SpringBoot很陌生。我创建了一个带有服务类的示例应用程序

下面是我的SpringBootApplication课程

@SpringBootApplication
public class SampleApplication {

    @Autowired
    static AWSService awsService;

    public static void main(String[] args) {

        SpringApplication.run(SampleApplication.class, args);
        awsService.getCertificate();  // Getting an NPE at this point

    }

}

AWS服务类

@Service
public class AWSService {

    public AWSService() {

    }

    private final Log log = new Log(getClass().getSimpleName());

    public void getCertificate() {
        String accessKey="";
        String secretKey="";
        try {
            Scanner awsCredentials = new Scanner(new File(Constants.AWS_CREDENTIALS));
            accessKey=awsCredentials.next();
            secretKey=awsCredentials.next();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey,secretKey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(
                new AWSStaticCredentialsProvider(basicAWSCredentials)).build();
        S3Object s3object = s3Client.getObject(
                new GetObjectRequest(Constants.S3_BUCKET_NAME, Constants.S3_KEY_NAME));
        String temporaryCertificatePath = storeCertificate(s3object);
        Constants.setKeyStoreFile(temporaryCertificatePath);
    }

    private String storeCertificate(S3Object s3Object) {
        try {
            File certificate = File.createTempFile("signingKey",".p12");
            OutputStream outputStream = new FileOutputStream(certificate);
            byte buffer [] = IOUtils.toByteArray(s3Object.getObjectContent());
            outputStream.write(buffer);
            certificate.deleteOnExit();
            return certificate.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }
}

下面是我得到的错误

Exception in thread "main" java.lang.NullPointerException
2017-02-27 13:24:04.023 at in.juspay.SampleApplication.main(SampleApplication.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 INFO   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
798 at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

我的应用程序类中有Autowired服务,但是我得到了一个NullPointerException。如果我正确理解Spring的@Service,那么@Autowire应该负责对象的初始化。那么,为什么我在那一点上得到了NPE


共 (2) 个答案